package com.swust.ipmsg.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.swust.ipmsg.activity.MessageActivity;
import com.swust.ipmsg.util.IPMsg;
import com.swust.ipmsg.util.Packet;
import com.swust.ipmsg.util.Person;

import android.R.bool;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;

public class PacketInternet {
	
	
	Person me;
	//还真心需要
	private static ArrayList<Map<Integer, Person>> friend = new ArrayList<Map<Integer, Person>>();
	private static Map<Integer, Person> friendMap = new HashMap<Integer, Person>();// 当前在线用户
	

	private static final int BUFFER_LENGTH = 1024;
	private static final String BROADCAST_ADDRESS = "255.255.255.255";// *作为上线、下线多播组的地址
																		// 10.10.1.255
	private static final String LOCALHOST_ADDRESS = "192.168.1.112";// *某个机器的地址
	private static final String MULTICAST_ADDRESS = "192.168.1.1";// *作为群聊的多播组的地址
	Receive receive = null;
	
	
	static int port = IPMsg.IPMSG_DEFAULT_PORT;// 定义端口，用整型数据表（整数）示端口号
	public static DatagramSocket socket = null;// 定义多播类型的套接字
	static DatagramPacket datagramPacket = null;
	String hostName = null;
	
	public PacketInternet() {
	}
	
	public PacketInternet (Person me){
		this.me = me;
	}
	
	
	
	public static void sendMessage(Packet packet,String IP_ADDRESS) {
		try {
			socket = new DatagramSocket(port);
			//Log.v("SocketInit", "succeed!");
		} catch (Exception e) {
			e.printStackTrace();
			//Log.e("SocketInit", "failed");
		}
		
		System.out.println("\nbroadcastMessage Run Succeed:"+packet.toString());
		byte[] b = packet.getPacketBytes();
		// 接受的数据包长度为length个字节。 DatagramPacket对象中包括通过DatagramSocket传输的数据。
		datagramPacket = new DatagramPacket(b, b.length);// 创建一个DatagramPacket对象接收数据
		try {
			datagramPacket.setAddress(InetAddress.getByName(IP_ADDRESS));
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}// 集设定接口的网络逻辑地址的目标主机
		// 设置目标主机的IP地址。
		datagramPacket.setPort(port);// 设置这个数据包目标主机的端口号。
		try {
			socket.send(datagramPacket);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Send Succeed!");
		
		System.out.println("packet Succeed!");
		socket.close();
	}
	
	/**
	 * 把协议包广播到整个群组中
	 * @param packet 要发送的包
	 * @throws SocketException
	 */
	public static void broadcastMessage(Packet packet) {
		sendMessage(packet,BROADCAST_ADDRESS);
	}
	
	
	public class Receive implements Runnable {

		public MulticastSocket recieveSocket;
		
		public Receive() {
		}
		public String waitForResponse() throws IOException {
			// 接收消息事件
			while (true) {

				Bundle bundle = new Bundle();
				Message msg = new Message();
				byte[] b = new byte[BUFFER_LENGTH];
				datagramPacket = new DatagramPacket(b, b.length);
				recieveSocket.receive(datagramPacket);
				System.out.println("Recieve Succeed!");
				String information = datagramPacket.getData().toString();
				information = information.trim();
				System.out.println(information);
				Packet packet = new Packet(information);
				information = packet.getAdditionalSection();
				Log.d("Thread......", "mThread......");

				if (datagramPacket.getPort() == port) {
					System.out.println("\nReturn Succeed!");
					msg.arg1 = 1;
					bundle.putString("information", information);
					msg.setData(bundle);// 设置一组随意的数据值
					MessageActivity.myHandler.sendMessage(msg);
				}
			}
		}
		
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				System.out.println("recieve start!");
				recieveSocket = new MulticastSocket(port);
				System.out.println("socket successed!");
				recieveSocket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
				System.out.println("join group successed!");
				waitForResponse();
				System.out.println("recieve run successed!");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("Thread run error!");
				
			}
		}
	}
	
	
	
}
